package com.heima.scan.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.heima.aliyun.green.AliyunGreenTemplate;
import com.heima.common.contants.MessageConstants;
import com.heima.scan.service.NewsScanService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NewsScanServiceImpl implements NewsScanService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private AliyunGreenTemplate alarmTemplate;

    /**
     * 文章内容审核
     *
     * @param newsId
     * @param text
     * @param images
     */
    @Override
    public void scan(Long newsId, String text, List<String> images) throws Exception {
        // 初始审核状态
        String suggestion = "pass";
        String reason = "审核通过";

        // 1、文本审核
        Map<String, String> resultmap = alarmTemplate.textScan(text);
        suggestion = resultmap.get("suggestion");
        if (!StrUtil.equals("pass",suggestion)){
            reason="文本中包含敏感信息";
        }

        // 2、图片审核
        if ("pass".equals(suggestion) && CollectionUtil.isNotEmpty(images)){
            resultmap = alarmTemplate.imageScanByUrl(images);
            suggestion = resultmap.get("suggestion");
            if (!StrUtil.equals("pass",suggestion)){
                reason="图片中包含敏感信息";
            }
        }
        // 3、将审核结果发送到MQ
        sendResultMessage(newsId,suggestion,reason);
    }

    /**
     * 发送消息
     * @param newsId 文章id
     * @param suggestion 审核结果
     * @param reason 原因
     */
    private void sendResultMessage(Long newsId, String suggestion, String reason) {
        // 封装需要检测的数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("newsId",newsId);
        map.put("suggestion", suggestion);
        map.put("reason", reason);
        // 发送消息
        rabbitTemplate.convertAndSend(MessageConstants.GREEN_SCAN_RESULT_EXCHANGE,MessageConstants.NEWS_SCAN_KEY, JSONUtil.toJsonStr(map));
    }
}
